package edu.neumont.csc380.filters;

import javax.ws.rs.core.Response;

import org.apache.cxf.configuration.security.AuthorizationPolicy;
import org.apache.cxf.jaxrs.ext.RequestHandler;
import org.apache.cxf.jaxrs.model.ClassResourceInfo;
import org.apache.cxf.message.Message;

/**
 * The purpose of this class is to provide user authentication. Authentication is done using the Authentication header
 * with a Base64 encoded username and password.
 * @author Jake Heimbouch
 *
 */
public class AuthenticationHandler implements RequestHandler {

    public Response handleRequest(Message m, ClassResourceInfo resourceClass) {
        AuthorizationPolicy policy = (AuthorizationPolicy)m.get(AuthorizationPolicy.class);
        if(policy != null){ // Does the Header Contain the Authentication parameter?
        	String username = policy.getUserName();
            String password = policy.getPassword(); 
            if (isAuthenticated(username, password)) {
                // let request to continue
                return null;
            } else {
                // authentication failed, return a 401 to the client
                return Response.status(401).header("WWW-Authenticate", "Basic").build();
            }
        }else{ // Return a 401 because the header did not contain Authentication
        	return Response.status(401).header("WWW-Authenticate", "Basic").build();
        }        
    }
    
    /**
     * Verifies if the username and password is "admin" and "prime"
     * @param username
     * @param password
     * @return if the username and password match
     */
    public boolean isAuthenticated(String username, String password){
    	return (username.equals("admin") && password.equals("prime"));
    }

}